using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common;
using DotNetNuke.Modules.NBrightEspace.Components;
using NBrightCore.common;
using NBrightCore.render;
using NBrightDNN;

namespace DotNetNuke.Modules.NBrightEspace
{

    public class EspaceModuleBase : NBrightDNN.controls.BaseAdminPage
    {

        public EspaceController ObjEspaceCtrl;

        protected override void OnInit(EventArgs e)
        {
            
            //check if we have a skinsrc, if not add it and reload. NOTE: Where just asking for a infinate loop here, but DNN7.2 doesn't leave much option.
            const string skinSrcAdmin = "?SkinSrc=%2fDesktopModules%2fNBright%2fNBrightEspace%2fSkins%2fNWB_nbright%2fNormal";
            if (Utils.RequestParam(Context, "SkinSrc") == "" && CtrlTypeCode != "CLIENTVIEW")
            {
                var ctl = Utils.RequestParam(Context, "ctl");
                if (ctl == "")
                {
                    // no DNN ctrl, must be back Office load page, don't use EditUrl 
                    Response.Redirect(Globals.NavigateURL() + skinSrcAdmin, true);                    
                }
                else
                {
                    var itemid = Utils.RequestParam(Context, "itemid");
                    if (Utils.IsNumeric(itemid))
                        Response.Redirect(EditUrl("itemid", itemid, ctl) + skinSrcAdmin, true);
                    else
                        Response.Redirect(EditUrl(ctl) + skinSrcAdmin, true);                    
                }


                Context.ApplicationInstance.CompleteRequest();  // do this to stop iis throwing error
            }

            var obj = new EspaceController();
            base.ObjCtrl = obj;
            ObjEspaceCtrl = obj;

            // get custom theme folder from settings.
            var objCtrl = new EspaceController();
            var objSettings = objCtrl.GetByTypeCode("SETTINGS");
            var themeFolder = "";
            if (objSettings != null) themeFolder = objSettings.GetXmlProperty("genxml/textbox/txtthemefolder");
            base.TemplateThemeFolder = themeFolder;
            base.PrimaryTemplateMapPath = MapPath(ControlPath); // don;t use default portal root for templates  

            base.OnInit(e);




        }

        #region "presistance methods"


        public void DeleteData(Repeater rp1)
        {
            var itemId = GenXmlFunctions.GetHiddenField(rp1, "ItemID");

            if (itemId == "")
            { // No valid itemid on XML, take from current id.  
                itemId = ItemId;
            }

            if (Utils.IsNumeric(itemId))
            {
                ObjCtrl.Delete(Convert.ToInt32(itemId));
            }
        }

        public void DeleteData(int itemID)
        {
            ObjCtrl.Delete(itemID);
        }

        public void DeleteArticleData(int itemID)
        {
            ObjEspaceCtrl.ClearArticleListFromDb(itemID, EntityTypeCode);
        }

        #endregion

        #region "methods"

        public void UpdateSelected(string selectedType)
        {
            var selItemId = UInfo.SelItemId;
            UInfo.SelType = "";
            UInfo.Save();

            if ((Utils.IsNumeric(selItemId)) & (Utils.IsNumeric(ItemId)))
            {
                var objCInfo = ObjCtrl.Get(Convert.ToInt32(selItemId));
                var objInfo = ObjCtrl.Get(Convert.ToInt32(ItemId));

                if (((objInfo == null)) & ((objCInfo != null)))
                {
                    // No Task exists, must be being created by link from client, so create new entry
                    objInfo = new NBrightInfo();
                    objInfo.ItemID=-1;
                    objInfo.TypeCode = EntityTypeCode;
                    //get template and populate with new data
                    var rp1 = GenXmlFunctions.InitRepeater(objInfo, TemplCtrl.GetTemplateData(CtrlTypeCode + "_Detail.html", Utils.GetCurrentCulture()));
                    //Get format XML from new repeater so XML is created.
                    objInfo.XMLData = GenXmlFunctions.GetGenXml(rp1);
                    // update and reassign id, so we don;t get duplicate
                    objInfo.ItemID = ObjCtrl.Update(objInfo);                   
                    ItemId = Convert.ToString(objInfo.ItemID);
                }


                if (((objInfo != null)) & ((objCInfo != null)))
                {
                    var xmlDoc = new XmlDataDocument();
                    var xmlCDoc = new XmlDataDocument();

                    xmlDoc.LoadXml(objInfo.XMLData);
                    xmlCDoc.LoadXml(objCInfo.XMLData);

                    switch (selectedType.ToLower())
                    {
                        case "client":
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtclientref");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtusername");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtclientname");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtcompanyname");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtpersonalemail");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/clientid", "genxml/hidden/itemid");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/clientref", "genxml/textbox/txtclientref");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/clientname", "genxml/textbox/txtclientname");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/companyname", "genxml/textbox/txtcompanyname");

                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtclientadd1");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtclientadd2");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtclientadd3");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtclientpc");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txttva");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txtsiret");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txttel1");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/textbox/txttel2");
                            break;
                        case "project":
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/projectid", "genxml/hidden/itemid");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/projectref", "genxml/hidden/projectref");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/projectname", "genxml/textbox/txtprojectname");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/liveurl", "genxml/textbox/txtliveurl");
                            break;
                        case "website":
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/websiteid", "genxml/hidden/itemid");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/websiteref", "genxml/hidden/websiteref");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/websitename", "genxml/textbox/txtwebsitename");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/websiteurl", "genxml/hidden/txtprimaryurl");
                            break;
                        case "url":
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/urlselectedid", "genxml/hidden/itemid");
                            GenXmlFunctions.MergeXmlNodeText(xmlDoc, xmlCDoc, "genxml/hidden/urlselected", "genxml/textbox/txturl");
                            break;

                    }

                    objInfo.XMLData = xmlDoc.OuterXml;

                    if (selectedType.ToLower() == "project")
                    {
                        objInfo.SetXmlProperty("genxml/hidden/websiteid","");
                        objInfo.SetXmlProperty("genxml/hidden/websiteref","");
                        objInfo.SetXmlProperty("genxml/hidden/websitename","");
                        objInfo.SetXmlProperty("genxml/hidden/websiteurl","");
                    }
                    if (selectedType.ToLower() == "website")
                    {
                        objInfo.SetXmlProperty("genxml/hidden/projectid", "");
                        objInfo.SetXmlProperty("genxml/hidden/projectref", "");
                        objInfo.SetXmlProperty("genxml/hidden/projectname", "");
                        objInfo.SetXmlProperty("genxml/hidden/liveurl", "");
                    }
                    if (selectedType.ToLower() == "clientclear")
                    {
                        objInfo.SetXmlProperty("genxml/hidden/projectid", "");
                        objInfo.SetXmlProperty("genxml/hidden/projectref", "");
                        objInfo.SetXmlProperty("genxml/hidden/projectname", "");
                        objInfo.SetXmlProperty("genxml/hidden/liveurl", "");
                        objInfo.SetXmlProperty("genxml/hidden/websiteid", "");
                        objInfo.SetXmlProperty("genxml/hidden/websiteref", "");
                        objInfo.SetXmlProperty("genxml/hidden/websitename", "");
                        objInfo.SetXmlProperty("genxml/hidden/websiteurl", "");
                    }


                    ObjCtrl.Update(objInfo);
                }
            }
        }

        public int AddXrefRecord(string typeCode)
        {
            var selId = UInfo.SelItemId;

            if ((Utils.IsNumeric(selId)) & (Utils.IsNumeric(ItemId)))
            {
                var objCInfo = ObjCtrl.Get(Convert.ToInt32(selId));
                var objInfo = ObjCtrl.Get(Convert.ToInt32(ItemId));

                if (((objInfo != null)) & ((objCInfo != null)))
                {
                    var objXref = new NBrightInfo();

                    objXref.ItemID = -1;
                    objXref.TypeCode = typeCode + ItemId;
                    objXref.XMLData = "<root><parentid>" + ItemId + "</parentid><xref>" + selId + "</xref><linkedxref></linkedxref></root>";
                    return ObjCtrl.Update(objXref);
                }
            }
            return -1;
        }

        public void AddXrefRecordRev(string typeCode, int linkedxref)
        {
            var selId = UInfo.SelItemId;

            if ((Utils.IsNumeric(selId)) & (Utils.IsNumeric(ItemId)))
            {
                var objCInfo = ObjCtrl.Get(Convert.ToInt32(selId));
                var objInfo = ObjCtrl.Get(Convert.ToInt32(ItemId));

                if (((objInfo != null)) & ((objCInfo != null)))
                {
                    var objXref = new NBrightInfo();

                    objXref.ItemID = -1;
                    objXref.TypeCode = typeCode + selId;
                    objXref.XMLData = "<root><parentid>" + selId + "</parentid><xref>" + ItemId + "</xref><linkedxref>" + linkedxref.ToString("") + "</linkedxref></root>";
                    var newId  = ObjCtrl.Update(objXref);
                    //update linked ref
                    var objLink = ObjCtrl.Get(linkedxref);
                    if (objLink != null)
                    {
                        objLink.XMLData = GenXmlFunctions.SetGenXmlValue(objLink.XMLData, "root/linkedxref", newId.ToString(""));
                        ObjCtrl.Update(objLink);
                    }
                }
            }
        }

        #endregion

        #region "Item Soft Locks"

        public void CancelLock(Repeater rp1)
        {
            if (GenXmlFunctions.GetHiddenField(rp1, "lockedby").StartsWith(UserInfo.Username + " on"))
            {
                var objInfo = GetData();
                if ((objInfo != null))
                {
                    ReleaseLock(objInfo);
                    ObjCtrl.Update(objInfo);
                }
            }
        }

        public void SetLock()
        {
            var objInfo = GetData();
            if (objInfo != null)
            {
                if (!string.IsNullOrEmpty(objInfo.XMLData))
                {
                    var xmlDoc = new XmlDataDocument();

                    xmlDoc.LoadXml(objInfo.XMLData);

                    var xmlNod = xmlDoc.SelectSingleNode("genxml/hidden/lockedby");
                    if ((xmlNod != null))
                    {
                        if (string.IsNullOrEmpty(xmlNod.InnerXml))
                        {
                            GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/lockedby", UserInfo.Username + " on " + Convert.ToString(DateTime.Now));
                            GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/htmldisplaylockedby", "", false);
                            objInfo.XMLData = xmlDoc.OuterXml;
                            ObjCtrl.Update(objInfo);
                        }
                        else
                        {
                            if (!xmlNod.InnerText.StartsWith(UserInfo.Username + " on"))
                            {
                                GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/htmldisplaylockedby", "<div class=\"Espace_LockDiv\">Locked by " + xmlNod.InnerText + "</div>", false);
                                objInfo.XMLData = xmlDoc.OuterXml;
                                ObjCtrl.Update(objInfo);
                            }
                        }
                    }
                }
            }
        }

        public void ReleaseLock(NBrightInfo objInfo, bool ForceRelease = false)
        {
            if (objInfo != null)
            {
                var xmlDoc = new XmlDataDocument();
                xmlDoc.LoadXml(objInfo.XMLData);
                var xmlNod = xmlDoc.SelectSingleNode("genxml/hidden/lockedby");
                if ((xmlNod != null))
                {
                    if (xmlNod.InnerText.StartsWith(UserInfo.Username + " on") | ForceRelease)
                    {
                        GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/lockedby", "");
                        GenXmlFunctions.ReplaceXmlNode(xmlDoc, "genxml/hidden/htmldisplaylockedby", "", false);
                        objInfo.XMLData = xmlDoc.OuterXml;
                        ObjCtrl.Update(objInfo);
                    }
                }
            }
        }

        public bool IsItemLocked(Repeater rp1)
        {
            if (!string.IsNullOrEmpty(GenXmlFunctions.GetHiddenField(rp1, "htmldisplaylockedby")))
            {
                return true;
            }
            return false;
        }

        public void SetUpdateMsgIfLocked(Repeater rp1, string cmdCtrlName, string LockMsg)
        {
            if (IsItemLocked(rp1))
            {
                if (!GenXmlFunctions.GetHiddenField(rp1, "htmldisplaylockedby").StartsWith(UserInfo.Username + " on"))
                {
                    if ((rp1.Items[0].FindControl(cmdCtrlName) != null))
                    {
                        ((LinkButton)rp1.Items[0].FindControl(cmdCtrlName)).Attributes.Add("onClick", "javascript:return confirm('" + LockMsg + "');");
                    }
                }
            }
        }

        #endregion

        #region "Base Events"

        public object UpdateDetailNoValidate(Repeater rpData, string typeCode, string uploadFolderMapPath, string itemId = "0")
        {
            var objInfo = (NBrightInfo)base.UpdateDetailNoValidate(rpData, EntityTypeCode, "");

            if (objInfo != null)
            {

                GenXmlFunctions.SetHiddenField(rpData, "dteModifiedDate", Convert.ToString(DateTime.Now));

                //move txtLog to teLog, if txtLog exists in form.
                string strLog = GenXmlFunctions.GetField(rpData, "txtLog");
                if (!string.IsNullOrEmpty(strLog))
                {
                    string strTeLog = GenXmlFunctions.GetField(rpData, "AuditLog");
                    strTeLog = Convert.ToString(DateTime.Now) + " - " + strLog + Environment.NewLine + strTeLog;
                    GenXmlFunctions.SetField(rpData, "txtLog", "");
                    GenXmlFunctions.SetField(rpData, "AuditLog", strTeLog);
                }

                //move txtTimeLog to teLog, if txtLog exists in form.
                string strTotalHours = GenXmlFunctions.GetField(rpData, "TotalHours");
                //string strTimeHours = GenXmlFunctions.GetField(rpData, "txtTimeHours");
                var strTimeHours = GenXmlFunctions.GetField(rpData, "ddlHours") + "." + GenXmlFunctions.GetField(rpData, "ddlMins");

                if (!string.IsNullOrEmpty(strTimeHours))
                {
                    if (Utils.IsNumeric(strTimeHours))
                    {
                        if (Convert.ToDecimal(strTimeHours,CultureInfo.GetCultureInfo("en-US")) > 0)
                        {
                            if (!Utils.IsNumeric(strTotalHours)) strTotalHours = "0";
                            strTotalHours = (Convert.ToDecimal(strTotalHours, CultureInfo.GetCultureInfo("en-US")) + Convert.ToDecimal(strTimeHours, CultureInfo.GetCultureInfo("en-US"))).ToString(CultureInfo.GetCultureInfo("en-US"));
                            GenXmlFunctions.SetField(rpData, "TotalHours", strTotalHours);

                            string strTimeLog = GenXmlFunctions.GetField(rpData, "txtTimeLog");
                            string strTimeDate = GenXmlFunctions.GetField(rpData, "txtTimeInpDate");
                            string strTimeEmpl = GenXmlFunctions.GetField(rpData, "ddlTimeEmployee");
                            if (strTimeDate == "") strTimeDate = Convert.ToString(DateTime.Now);
                            if (Utils.IsDate(strTimeDate))
                            {
                                strTimeDate = String.Format("{0:s}", Convert.ToDateTime(strTimeDate)).Substring(0, 10);
                            }
                            GenXmlFunctions.SetField(rpData, "ddlHours", "0");
                            GenXmlFunctions.SetField(rpData, "ddlMins", "0");
                            GenXmlFunctions.SetField(rpData, "txtTimeLog", "");
                            GenXmlFunctions.SetField(rpData, "txtTimeInpDate", "");
                            GenXmlFunctions.SetField(rpData, "ddlTimeEmployee", "");


                            //create a time record for reporting.
                            var obj = new NBrightInfo();
                            obj.ItemID = -1;
                            obj.TypeCode = "PROJTIME";
                            //get template and populate with new data
                            var rpTime = GenXmlFunctions.InitRepeater(obj, TemplCtrl.GetTemplateData("PROJTIME_Detail.html", Utils.GetCurrentCulture()));
                            GenXmlFunctions.SetField(rpTime, "projectid", objInfo.ItemID.ToString(CultureInfo.InvariantCulture));
                            GenXmlFunctions.SetField(rpTime, "txthours", strTimeHours);
                            GenXmlFunctions.SetField(rpTime, "txtemployee", strTimeEmpl);
                            GenXmlFunctions.SetField(rpTime, "txtdate", strTimeDate);
                            GenXmlFunctions.SetField(rpTime, "txtlog", strTimeLog);
                            //Get format XML from new repeater so XML is created.
                            obj.XMLData = GenXmlFunctions.GetGenXml(rpTime);
                            // update and reassign id, so we don;t get duplicate
                            obj.ItemID = ObjCtrl.Update(obj);
                        }
                    }
                }


                // Add costs
                var strAllocCost = GenXmlFunctions.GetHiddenField(rpData, "hidAllocatedCosts");
                var strCosts = GenXmlFunctions.GetFieldAsDouble(rpData, "txtCostsAmt");
                if (strCosts > 0)
                {
                    if (!Utils.IsNumeric(strAllocCost)) strAllocCost = "0";

                    strAllocCost = (Convert.ToDouble(strAllocCost, CultureInfo.GetCultureInfo("en-US")) + strCosts).ToString(CultureInfo.GetCultureInfo("en-US"));

                    GenXmlFunctions.SetField(rpData, "hidAllocatedCosts", strAllocCost);

                    string strCostsLog = GenXmlFunctions.GetField(rpData, "txtCostsLog");
                    string strCostsDate = GenXmlFunctions.GetField(rpData, "txtCostsInpDate");

                    GenXmlFunctions.SetField(rpData, "txtCostsAmt", "0");
                    GenXmlFunctions.SetField(rpData, "txtCostsLog", "");
                    GenXmlFunctions.SetField(rpData, "txtCostsInpDate", "");

                    //create a time record for reporting.
                    var obj = new NBrightInfo();
                    obj.ItemID = -1;
                    obj.TypeCode = "PROJCOST";
                    //get template and populate with new data
                    var rpCost = GenXmlFunctions.InitRepeater(obj, TemplCtrl.GetTemplateData("PROJCOST_Detail.html", Utils.GetCurrentCulture()));
                    GenXmlFunctions.SetField(rpCost, "projectid", objInfo.ItemID.ToString(CultureInfo.InvariantCulture));
                    GenXmlFunctions.SetField(rpCost, "txtcosts", strCosts.ToString(CultureInfo.GetCultureInfo("en-US")));
                    GenXmlFunctions.SetField(rpCost, "txtdate", strCostsDate);
                    GenXmlFunctions.SetField(rpCost, "txtlog", strCostsLog);
                    //Get format XML from new repeater so XML is created.
                    obj.XMLData = GenXmlFunctions.GetGenXml(rpCost);
                    // update and reassign id, so we don;t get duplicate
                    obj.ItemID = ObjCtrl.Update(obj);
                }


                //rebuild xml
                objInfo.XMLData = GenXmlFunctions.GetGenXml(rpData);

                EspaceFunctions.ReleaseLock(objInfo, UserInfo, true);

                objInfo.ModifiedDate = DateTime.Now;

                ObjCtrl.Update(objInfo);

                if (Convert.ToString(objInfo.ItemID) != ItemId)
                {
                    ItemId = Convert.ToString(objInfo.ItemID); // make sure base class has correct ID                    
                    GenXmlFunctions.SetHiddenField(rpData, "ItemID", ItemId);
                    //rebuild xml
                    objInfo.XMLData = GenXmlFunctions.GetGenXml(rpData);
                    objInfo.ItemID = ObjCtrl.Update(objInfo);
                }

            }
            return objInfo;
        }

        public void OnInitDetail(Repeater rpData)
        {
            var templateData = TemplCtrl.GetTemplateData(EntityTypeCode + "_Detail.html", Utils.GetCurrentCulture());
            templateData = TemplCtrl.ReplaceResourceString(templateData);
            rpData.ItemTemplate = new GenXmlTemplate(templateData);
        }

        #endregion

    }

}
